import Vue from 'vue'
import Vuex from 'vuex'
import user from '@/api/user'
import equApi from '@/api/equipment'
import Permission from "@/common/Permission.js";

Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		config: {},
		imgHost: 'fulala.oss-cn-hangzhou.aliyuncs.com',
		shareId: uni.getStorageSync('shareId'),
		outPutUid: uni.getStorageSync('outPutUid'),
		hasLogin: uni.getStorageSync('hasLogin'),
		token: uni.getStorageSync('token'),
		userInfo: uni.getStorageSync('userInfo'),
		inviteCode: uni.getStorageSync('inviteCode'),
		wxPay:'',
		userLocation: {
			longitude: 0,
			latitude: 0,
		}
	},
	mutations: {
		logout: (state) => {
			state.hasLogin = false
			state.token = ''
			state.userInfo = {}
			uni.removeStorageSync('hasLogin')
			uni.removeStorageSync('token')
			uni.removeStorageSync('userInfo')
		},
		setHasLogin: (state, data) => {
			state.hasLogin = data
			uni.setStorageSync('hasLogin', data)
		},
		setOutPutUid: (state, data) => {
			state.outPutUid = data
			uni.setStorageSync('outPutUid', data)
		},
		setShareId: (state, data) => {
			state.shareId = data
			uni.setStorageSync('shareId', data)
		},
		setToken: (state, data) => {
			state.token = data
			uni.setStorageSync('token', data)
		},
		setUserInfo: (state, data) => {
			state.userInfo = Object.assign({}, state.userInfo, data)
			uni.setStorageSync('userInfo', data)
		},
		setConfig(state, config) {
			state.config = Object.assign({}, state.config, config)
		},
		setUserLocation(state, data) {
			console.log('位置更新');
			state.userLocation = Object.assign({}, state.userLocation, data)
		},
		setInviteCode: (state, data) => {
			state.inviteCode = data
			uni.setStorageSync('inviteCode', data)
		},
		removeInviteCode: (state) => {
			state.inviteCode = ''
			uni.removeStorageSync('inviteCode')
		},
	},
	getters: {},
	actions: {
		user(context, data) {
			user.index().then(res => {
				if (res.code === 1) {
					context.commit('setUserInfo', res.data.user)
				} else {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					})
				}
			})
		},
		async getLocation(context, data) {
			// #ifndef H5
			const permission = new Permission('scope.userLocation', '需要在设置中获取定位权限');
			const result = await permission.request();
			if (!result) {
				return;
			}

			const [locationError, locationRes] = await uni.getLocation({
				type: 'gcj02'
			});
			console.log(locationError, locationRes);
			if (locationError) {
				throw new Error('位置获取失败');
			}
			// #endif
			// #ifdef H5
			const locationRes = {
				longitude: 0,
				latitude: 0
			}
			// #endif
			context.commit('setUserLocation', {
				longitude: locationRes.longitude,
				latitude: locationRes.latitude,
			})
		},
	}
})

export default store
